package com.xuecheng.media.service.impl;


import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.exception.XuechengOnlineException;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.BigFilesService;
import com.xuecheng.media.service.MediaFileService;
import com.xuecheng.model.RestResponse;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class BigFilesServiceImpl implements BigFilesService {
    @Autowired
    MediaFilesMapper mediaFilesMapper;

    @Autowired
    MinioClient minioClient;

    @Autowired
    BigFilesService currentProxy;

    @Autowired
    MediaProcessMapper mediaProcessMapper;

    //视频桶
    @Value("${minio.bucket.videofiles}")
    private String bucket_videofiles;
    /**
     * 检查文件是否存在
     * @param fileMd5 文件的MD5
     * @return
     */
    @Override
    public RestResponse<Boolean> checkFile(String fileMd5) {
        //查询文件信息
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if(mediaFiles != null){
            //桶
            String bucket = mediaFiles.getBucket();

            //存储目录
            String filePath = mediaFiles.getFilePath();

            //文件流
            InputStream stream = null;

            try {
                stream = minioClient.getObject(
                        GetObjectArgs.builder()
                                .bucket(bucket)
                                .object(filePath)
                                .build());
                if(stream != null){
                    //文件已存在
                    return RestResponse.success(true);
                }
            } catch (Exception e) {

            }

        }
        //文件不存在
        return RestResponse.success(false);
    }



    /**
     * 检查分块是否存在
     *
     * @param fileMd5 文件的MD5
     * @param chunk   分块序号
     * @return
     */
    @Override
    public RestResponse<Boolean> checkChunk(String fileMd5, int chunk) {

        //得到分块文件目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);

        //得到分块文件的路径  (分块文件目录 + 分块序号）
        String chunkFilePath = chunkFileFolderPath + chunk;

        //文件流
        InputStream fileInputStream = null;
        try{
            fileInputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucket_videofiles)
                            .object(chunkFilePath)
                            .build());
            if(fileInputStream != null){
                //分块已经存在
                return RestResponse.success(true);
            }
        }catch (Exception e){

        }
        //分块未存在
        return RestResponse.success(false);
    }


    //得到分块文件目录
    private String getChunkFileFolderPath(String fileMd5) {
        //video/b/1/b1699957c0abd88ca8c1376d7693d448/chunk/0  将MD5值前两个作为目录名称

        //substring---左开右闭
        return fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5
                + "/" + "chunk" + "/";
    }



    /**
     * 上传文件
     *
     * @param fileMd5            文件MD5值
     * @param chunk              分块序号
     * @param localChunkFilePath 分块文件本地路径
     * @return
     */
    @Override
    public RestResponse uploadChunk(String fileMd5, int chunk, String localChunkFilePath) {

        //得到分块文件的目录路径
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);

        //得到分块文件的路径(分块文件目录路径 + 分块序号）
        String chunkFilePath = chunkFileFolderPath + chunk;

        //mimeType
        String mimeType = getMimeType(null);

        //将文件存储到minio
        boolean b = addMediaFilesToMinio(localChunkFilePath, mimeType, bucket_videofiles, chunkFilePath);
        if(!b){
            log.debug("上传分块文件失败：{}",chunkFilePath);
            return RestResponse.validfail(false,"上传分块失败");
        }
        log.debug("上传分块文件成功：{}",chunkFilePath);
        return RestResponse.success(true,"上传分块成功");
    }



    //获取媒体类型(mimeType)
    private String getMimeType(String extension) {
        if(extension == null){
            extension = "";
        }
        //根据扩展名取出mimeTyoe
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        //通用mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if(extensionMatch != null){
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;

    }

    /**
     * 将文件写入minio
     * @param localFilePath   文件地址
     * @param mimeType   媒体类型
     * @param bucketFiles   桶
     * @param objectName  对象名称
     */
    private boolean addMediaFilesToMinio(String localFilePath, String mimeType, String bucketFiles, String objectName) {

        try {
            UploadObjectArgs testbucket = UploadObjectArgs.builder()
                    .bucket(bucketFiles)
                    .object(objectName)
                    .filename(localFilePath)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(testbucket);
            log.debug("上传文件到minio成功，bucket：{}，objectName：{}",bucketFiles,objectName);
            System.out.println("上传成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件到minio出错，bucket:{},objectName:{} 错误原因：{}",bucketFiles,objectName,e.getMessage());
            XuechengOnlineException.cast("上传文件到文件系统失败");
        }
        return false;
    }


    /**
     * 合并分块
     *
     * @param companyId           机构id
     * @param fileMd5             文件MD5值
     * @param chunkTotal          分块总和
     * @param uploadFileParamsDto 文件信息
     * @return
     */
    @Override
    public RestResponse mergechunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {

        //=====获取分块文件路径============
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);

        //将分块文件路径组成 List<ComposeSource>
        List<ComposeSource> sourceObjectList = Stream.iterate(0, i -> ++i)
                .limit(chunkTotal)
                .map(i -> ComposeSource.builder()
                        .bucket(bucket_videofiles)
                        .object(chunkFileFolderPath.concat(Integer.toString(i)))
                        .build())
                .collect(Collectors.toList());

        //======合并======
        //文件名称
        String filename = uploadFileParamsDto.getFilename();

        //文件扩展名
        String extName = filename.substring(filename.lastIndexOf("."));

        //合并文件路径
        String mergeFilePath = getFilePathByMd5(fileMd5,extName);

        try {
            //合并文件
            ObjectWriteResponse response = minioClient.composeObject(
                    ComposeObjectArgs.builder()
                            .bucket(bucket_videofiles)
                            .object(mergeFilePath)
                            .sources(sourceObjectList)
                            .build());
            log.debug("合并文件成功：{}",mergeFilePath);
        } catch (Exception e) {
            log.debug("合并文件失败,fileMd5:{},异常:{}",fileMd5,e.getMessage(),e);
            return RestResponse.validfail(false,"合并文件失败");
        }


        //======验证MD5=========
        //下载合并后的文件
        File minioFile = downloadFileFromMinio(bucket_videofiles, mergeFilePath);
        if(minioFile == null){
            log.debug("下载合并后文件失败：{}",mergeFilePath);
            return RestResponse.validfail(false, "下载合并后文件失败。");
        }
        try(
                FileInputStream fileInputStream = new FileInputStream(minioFile)
        ){
            //minio上的文件MD5值
            String md5Hex = DigestUtils.md5Hex(fileInputStream);

            //比较MD5值，不一致说明文件不完整
            if(!fileMd5.equals(md5Hex)){
                return RestResponse.validfail(false, "文件合并校验失败，最终上传失败。");
            }

            //文件大小
            uploadFileParamsDto.setFileSize(minioFile.length());
        }catch (Exception e){
            log.debug("校验文件失败,fileMd5:{},异常:{}",fileMd5,e.getMessage(),e);
            return RestResponse.validfail(false, "文件合并校验失败，最终上传失败。");
        }finally {
            if(minioFile != null){
                minioFile.delete();
            }
        }

        //文件入库
        currentProxy.addMediaFilesToDb(companyId,fileMd5,uploadFileParamsDto,bucket_videofiles,mergeFilePath);

        //==========清除分块文件==============
        clearChunkFiles(chunkFileFolderPath,chunkTotal);
        return RestResponse.success(true);

    }

    /**
     * 得到合并后的文件地址
     * @param fileMd5  文件id---MD5值
     * @param extName   文件扩展名
     * @return
     */
    private String getFilePathByMd5(String fileMd5, String extName) {
        return fileMd5.substring(0,1) + "/"
                + fileMd5.substring(1,2) + "/"
                + fileMd5 + "/" + fileMd5 + extName;
    }

    /**
     * 清除分块文件
     * @param chunkFileFolderPath  分块文件路径
     * @param chunkTotal   分块文件总数
     */
    private void clearChunkFiles(String chunkFileFolderPath, int chunkTotal) {
        try{
            List<DeleteObject> deleteObjects = Stream.iterate(0, i -> ++i)
                    .limit(chunkTotal)
                    .map(i -> new DeleteObject(
                            chunkFileFolderPath.concat(Integer.toString(i))))
                    .collect(Collectors.toList());

            RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder()
                    .bucket("video")
                    .objects(deleteObjects)
                    .build();

            Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
            results.forEach(r ->{
                DeleteError deleteError = null;
                try{
                    deleteError = r.get();
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("清除分块文件失败,objectname:{}",deleteError.objectName(),e);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            log.error("清除分块文件失败,chunkFileFolderPath:{}",chunkFileFolderPath,e);
        }
    }

    /**
     * 从minio下载文件
     * @param bucketVideofiles  桶
     * @param mergeFilePath  对象名称
     */
    public File downloadFileFromMinio(String bucketVideofiles, String mergeFilePath) {

        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;

        try{
            InputStream stream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketVideofiles)
                            .object(mergeFilePath)
                            .build());
            //创建临时文件
            minioFile = File.createTempFile("minio", "merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(stream,outputStream);
            return minioFile;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Transactional   //通过代理对象调用
    public RestResponse addMediaFilesToDb(Long companyId, String fileMd5, UploadFileParamsDto uploadFileParamsDto, String bucket_files, String objectName) {
        //从数据库查询文件
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if(mediaFiles == null){
            mediaFiles = new MediaFiles();
            //拷贝基本信息
            BeanUtils.copyProperties(uploadFileParamsDto,mediaFiles);
            mediaFiles.setId(fileMd5);
            mediaFiles.setFileId(fileMd5);
            mediaFiles.setCompanyId(companyId);
            mediaFiles.setUrl("/" + bucket_files + "/" + objectName);
            mediaFiles.setBucket(bucket_files);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setStatus("1");

            //保存文件信息到文件表
            int insert = mediaFilesMapper.insert(mediaFiles);
            if(insert < 0){
                log.error("保存文件信息到数据库失败，{}",mediaFiles);
                XuechengOnlineException.cast("保存文件信息失败");
            }
            //添加到待处理任务表（如果是avi视频，才添加进来）
            addWaitingTask(mediaFiles);
            log.debug("保存文件信息到数据库成功,{}", mediaFiles.toString());
        }
        return RestResponse.success(true);
    }

    /**
     * 添加待处理任务
     * @param mediaFiles  媒资文件信息
     */
    private void addWaitingTask(MediaFiles mediaFiles) {
        //文件名称
        String filename = mediaFiles.getFilename();
        //文件扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //文件mimeType
        String mimeType = getMimeType(extension);
        //如果是avi视频--添加到视频待处理表
        if(mimeType.equals("video/x-msvideo")){  //avi默认mime格式
            MediaProcess mediaProcess = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles,mediaProcess);
            mediaProcess.setStatus("1");   //未处理
            mediaProcess.setFailCount(0);   //失败次数默认为0
            mediaProcessMapper.insert(mediaProcess);
        }
    }
}
